<?php
require_once('ObjectClasses/Post.php');
require_once('ObjectClasses/Comment.php');
require_once('DBConnection.php');

class PostHandler{
	private $db = NULL;
	
	const FILENAME = '0';
	const FILETYPE = '1';
	
	const TITLELENGTH = '2';
	const TEXTLENGTH = '3';
	
	public function __construct(DBConnection $db){
		$this->db = $db;
	}
	
	public function getPost(){
		
		$sql = "SELECT *, IFNULL((SELECT COUNT(*) as noc FROM postcomment WHERE postcomment.postid = post.postid GROUP BY post.postid), '0') as noc FROM post ORDER BY post.pdate DESC";

		$stmt = $this->db->Prepare($sql);

		$stmt->execute();
		
		$result = $stmt->get_result();
		
		$postArray = array();

		while ($p = $result->fetch_assoc()) {
			$obj = new Post;
			$obj->postTitle($p['title']);
			$obj->postText($p['ptext']);
			$obj->postDate($p['pdate']);
			$obj->postId($p['postid']);
			$obj->postNumberOfComments($p['noc']);
			$obj->postComments(self::getPostComments($p['postid']));
			if($p['pictureSrc'] != NULL){
				$obj->postPicture($p['pictureSrc']);
			}
			array_push($postArray, $obj);
		}
		
		
		
		return $postArray;
	}
	
	public function getPicturePost(){
		
		$sql = "SELECT *, IFNULL((SELECT COUNT(*) as noc FROM postcomment WHERE postcomment.postid = post.postid GROUP BY post.postid), '0') as noc FROM post WHERE post.pictureSrc IS NOT NULL ORDER BY post.pdate DESC";

		$stmt = $this->db->Prepare($sql);

		$stmt->execute();
		
		$result = $stmt->get_result();
		
		$postArray = array();

		while ($p = $result->fetch_assoc()) {
			$obj = new Post;
			$obj->postTitle($p['title']);
			$obj->postText($p['ptext']);
			$obj->postDate($p['pdate']);
			$obj->postId($p['postid']);
			$obj->postNumberOfComments($p['noc']);
			$obj->postComments(self::getPostComments($p['postid']));
			if($p['pictureSrc'] != NULL){
				$obj->postPicture($p['pictureSrc']);
			}
			array_push($postArray, $obj);
		}
		
		
		
		return $postArray;
	}
	
	public function getPostComments($pid){
		$sql = "SELECT postcomment.*, user.username FROM postcomment INNER JOIN user ON user.userid = postcomment.userid WHERE postid = ?";
		$stmt = $this->db->Prepare($sql);
		$stmt->bind_param('i', $pid);
		
		$stmt->execute();
		
		$result = $stmt->get_result();
		
		$commentArray = array();

		while ($c = $result->fetch_assoc()) {
			$obj = new Comment;
			$obj->commentText($c['commentText']);
			$obj->commentDate($c['commentDate']);
			$obj->commentId($c['postCommentId']);
			$obj->userId($c['userId']);
			$obj->commentUser($c['username']);
			array_push($commentArray, $obj);
		}
		
		return $commentArray;
	}
	
	public function getPostByTag($tag){
		
		$sql = "SELECT post.*, IFNULL((SELECT COUNT(*) as noc FROM postcomment WHERE postcomment.postid = post.postid GROUP BY post.postid), '0') as noc  FROM post INNER JOIN posttag ON posttag.postid = post.postid INNER JOIN tag ON tag.tagid = posttag.tagid WHERE tag.tagName = ? ORDER BY post.pdate DESC";

		$stmt = $this->db->Prepare($sql);
		
		$stmt->bind_param('s', $tag);

		$stmt->execute();
		
		$result = $stmt->get_result();
		
		$postArray = array();

		while ($p = $result->fetch_assoc()) {
			$obj = new Post;
			$obj->postTitle($p['title']);
			$obj->postText($p['ptext']);
			$obj->postDate($p['pdate']);
			$obj->postId($p['postid']);
			$obj->postNumberOfComments($p['noc']);
			$obj->postComments(self::getPostComments($p['postid']));
			if($p['pictureSrc'] != NULL){
				$obj->postPicture($p['pictureSrc']);
			}
			array_push($postArray, $obj);
		}
		return $postArray;
	}
	
	public function addComment($pid, $cText, $userId){
		$sql = "INSERT INTO postcomment (postid, commenttext, userid) VALUES (?, ?, ?)";
		
		$stmt = $this->db->Prepare($sql);
		
		$stmt->bind_param('isi', $pid, $cText, $userId);

		$stmt->execute();
	}
	
	public function removePostOrComment($id, $type){
		
		$idname;
		if($type == 'postcomment'){
			$idname = 'postCommentId';
		}else{
			$idname = 'postId';
		}
		$sql = "DELETE FROM $type WHERE $idname = ?";
		$stmt = $this->db->Prepare($sql);
		
		$stmt->bind_param('i', $id);

		$stmt->execute();
	}
	
	public function CreateNewPost($postTitle, $postText, $tagsArray, $filename){
		$sql = "INSERT INTO post (title, ptext, picturesrc) VALUES (?, ?, ?)";
		
		$stmt = $this->db->Prepare($sql);
		
		$stmt->bind_param('sss', $postTitle, $postText, $filename);

		$stmt->execute();
		
		$insert_id = $stmt->insert_id;
		
		foreach($tagsArray as $t){
			$tagId;
			switch($t){
				case 'Livet':
					$tagId = 1;
					break;
				case 'Design':
					$tagId = 2;
					break;
				case 'Webutveckling':
					$tagId = 3;
					break;
				case 'Skola':
					$tagId = 4;
					break;
				case 'Business':
					$tagId = 5;
					break;
				default:
					$tagId=0;
					break;
			}
			
			if($tagId > 0 && $tagId <= 5){
				$sql = "INSERT INTO posttag (postId, tagId) VALUES (?, ?)";
				$stmt = $this->db->Prepare($sql);
				$stmt->bind_param('ii', $insert_id, $tagId);
				$stmt->execute();
			}
		}
		
		//TODO: FIXA TAGSARRAY... MED mysqlfunktionsak kanske
	}
	
	public function SaveFile($file){
		
		$errorArray = array();
		$gotErrors = false;
		
		$target = 'bilder/'.$file['name'];

		if(!$this->PictureFileNameLength($target)){
			array_push($errorArray, self::FILENAME);
			$gotErrors = true;
		}
		
		if(!$this->FileIsImageType($file)){
			array_push($errorArray, self::FILETYPE);
			$gotErrors = true;
		}
		
		if(!$gotErrors){
			move_uploaded_file($file['tmp_name'], $target);
			return $target;
		}else{
			return $errorArray;
		}

	}
	
	public function PictureFileNameLength($target){ //kollar så att inte filnamnet är över 50tecken
		if(strlen($target) <= 50){
			return true;
		}
		return false;
	}
	
	public function FileIsImageType($file){ //kollar så att filen är ett bildformat
		$file =  pathinfo($file['name']);
		if(strtolower ($file['extension']) == 'jpg' || strtolower ($file['extension']) == 'jpeg' || strtolower ($file['extension']) == 'png' || strtolower ($file['extension']) == 'gif'){
			return true;
		}else{
			return false;
		}
	}
	public function titleLength($string){
		$regex = "/^.{3,30}$/"; //kollar längden på title-strängen
		if(preg_match($regex, $string)){
			return true;
		}else{
			return false;
		}
	}
	
	public function textLength($string){
		$regex = "/^.{10,}$/"; //kollar längden på text-strängen
		if(preg_match($regex, $string)){
			return true;
		}else{
			return false;
		}
	}
}

?>